package com.my.blog.website.controller.admin;


import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.my.blog.website.constant.WebConst;
import com.my.blog.website.controller.BaseController;
import com.my.blog.website.dto.LogActions;
import com.my.blog.website.dto.Types;
import com.my.blog.website.exception.TipException;
import com.my.blog.website.modal.Bo.RestResponseBo;
import com.my.blog.website.modal.Vo.ContentVo;
import com.my.blog.website.modal.Vo.MetaVo;
import com.my.blog.website.modal.Vo.UserVo;
import com.my.blog.website.service.IContentService;
import com.my.blog.website.service.ILogService;
import com.my.blog.website.service.IMetaService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by 13 on 2017/2/21.
 */
@Controller
@RequestMapping("admin/article")
@Transactional(rollbackFor = TipException.class)
public class ArticleController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ArticleController.class);

    @Resource
    private IContentService contentsService;

    @Resource
    private IMetaService metasService;

    @Resource
    private ILogService logService;

    /**
     * 查询发布、草稿状态的文章列表
     *
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping(value = "")
    public String index(@RequestParam(value = "page", defaultValue = "1") int page,
                        @RequestParam(value = "limit", defaultValue = "15") int limit, HttpServletRequest request) {
        /*ContentVoExample contentVoExample = new ContentVoExample();
        contentVoExample.setOrderByClause("created desc");
        contentVoExample.createCriteria().andTypeEqualTo(Types.ARTICLE.getType());
        PageInfo<ContentVo> contentsPaginator = contentsService.getArticlesWithpage(contentVoExample, page, limit);*/
        List<String> status = Lists.newArrayList();
        status.add(Types.PUBLISH.getType());
        status.add(Types.DRAFT.getType());

        UserVo user = this.user(request);
        PageInfo<ContentVo> contentsPaginator = contentsService.getArticlesWithTypeAndStatus(user.getUid() , null, status, page, limit);
        request.setAttribute("articles", contentsPaginator);

        List<MetaVo> categories = metasService.getMetas(user.getUid(),Types.CATEGORY.getType());
        request.setAttribute("categories", categories);

        return "admin/article_list";
    }

    /**
     * 查询发布、草稿状态的文章列表
     *
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping(value = "search")
    public String search(@RequestParam(value = "page", defaultValue = "1") int page,
                        @RequestParam(value = "limit", defaultValue = "15") int limit,
                         @RequestParam(value = "category") String category,
                         @RequestParam(value = "state") String status,
                         @RequestParam(value = "keyword") String keyword,
                         HttpServletRequest request) {
        List<String> statusList = Lists.newArrayList();
        if(StringUtils.isBlank(status)){
            statusList.add(Types.PUBLISH.getType());
            statusList.add(Types.DRAFT.getType());
            statusList.add(Types.DELETE.getType());
            // statusList.add(Types.PERSONAL.getType());
        }else{
            statusList.add(status);
        }

        List<String> categoryList = Lists.newArrayList();
        if(StringUtils.isNotBlank(category)){
            categoryList.add(category);
        }

        UserVo user = this.user(request);
        PageInfo<ContentVo> contentsPaginator = contentsService.getArticlesWithTitle(user.getUid(), null, statusList,categoryList, page, limit,keyword);

        request.setAttribute("articles", contentsPaginator);
        request.setAttribute("category",category);
        request.setAttribute("state",status);
        request.setAttribute("keyword",keyword);

        List<MetaVo> categories = metasService.getMetas(user.getUid(),Types.CATEGORY.getType());
        request.setAttribute("categories", categories);

        return "admin/article_list";
    }

    @GetMapping(value = "publish")
    public String newArticle(HttpServletRequest request) {
        UserVo user = this.user(request);
        List<MetaVo> categories = metasService.getMetas(user.getUid(), Types.CATEGORY.getType());
        request.setAttribute("categories", categories);

        List<MetaVo> tags = metasService.getMetas(user.getUid(), Types.TAG.getType());
        request.setAttribute("tags", tags);
        return "admin/article_edit";
    }

    @GetMapping(value = "{cid}")
    public String editArticle(@PathVariable String cid, HttpServletRequest request) {
        UserVo user = this.user(request);
        ContentVo contents = contentsService.getContents(cid);
        request.setAttribute("contents", contents);
        List<MetaVo> categories = metasService.getMetas(user.getUid(),Types.CATEGORY.getType());
        request.setAttribute("categories", categories);

        List<MetaVo> tags = metasService.getMetas(user.getUid(),Types.TAG.getType());
        request.setAttribute("tags", tags);

        request.setAttribute("active", "article");
        return "admin/article_edit";
    }

    /**
     * 发布文章
     *
     * @param contents
     * @param request
     * @return
     */
    @PostMapping(value = "publish")
    @ResponseBody
    public RestResponseBo publishArticle(ContentVo contents, HttpServletRequest request) {
        UserVo users = this.user(request);
        contents.setAuthorId(users.getUid());
        contents.setType(Types.ARTICLE.getType());
        if (StringUtils.isBlank(contents.getCategories())) {
            contents.setCategories("默认分类");
        }
        String result = contentsService.publish(contents);
        if (!WebConst.SUCCESS_RESULT.equals(result)) {
            return RestResponseBo.fail(result);
        }
        return RestResponseBo.ok();
    }

    /**
     * 更新文章
     *
     * @param contents
     * @param request
     * @return
     */
    @PostMapping(value = "modify")
    @ResponseBody
    public RestResponseBo modifyArticle(ContentVo contents, HttpServletRequest request) {
        UserVo users = this.user(request);
        contents.setAuthorId(users.getUid());
        contents.setType(Types.ARTICLE.getType());

        String result = contentsService.updateArticle(contents);
        if (!WebConst.SUCCESS_RESULT.equals(result)) {
            return RestResponseBo.fail(result);
        }
        return RestResponseBo.ok();
    }

    @RequestMapping(value = "delete")
    @ResponseBody
    public RestResponseBo delete(@RequestParam int cid, HttpServletRequest request) {
        String result = contentsService.deleteByCid(cid);
        logService.insertLog(LogActions.DEL_ARTICLE.getAction(), cid + "", request.getRemoteAddr(), this.getUid(request));
        if (!WebConst.SUCCESS_RESULT.equals(result)) {
            return RestResponseBo.fail(result);
        }
        return RestResponseBo.ok();
    }
}
